package org.example.server;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

@Component
public class UdpServer {
    @PostConstruct
    public void init() {
        try(DatagramSocket socket=new DatagramSocket(8085)) {
            byte[] buffer = new byte[1024];
            while (true){
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                socket.receive(packet);
                String s = new String(packet.getData(), 0, packet.getLength());
                if(s.startsWith("BUY:")){
                    String[] parts = s.split(":");
                    String stockCode = parts[1];
                    int userId = Integer.parseInt(parts[2]);
                    double price = Double.parseDouble(parts[3]);
                    System.out.println("BUY:"+stockCode+" "+userId+" "+price);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}